package com.ruoyi.netty.init;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class SocketServer {

    @Value("${socket.port:8088}")
    private int port;

    @Value("${netty.bossThread:1}")
    private int bossThread;

    @Resource
    private SocketInitializer socketInitializer;

    @Getter
    private ServerBootstrap serverBootstrap;

    /**
     * 初始化
     */
    private void init() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(bossThread);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(socketInitializer);
    }

    public void start() {
        this.init();
        this.serverBootstrap.bind(port);
        log.info("WebSocket服务启动成功，端口：{}", port);
    }

}
